package com.fyk.study.controller;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fyk.study.entity.User;
import com.fyk.study.exp.BusinessException;
import com.fyk.study.resp.ResultData;
import com.fyk.study.resp.ReturnCodeEnum;
import com.fyk.study.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping(value = "/user/add")
    public ResultData<Boolean> add(@RequestBody User user)
    {
        for (int i = 0; i < 20; i++) {
            User entity = new User();

            entity.setUsername(user.getUsername()+ IdUtil.simpleUUID().substring(0,4));
            entity.setPassword("123456");
            entity.setSex(1);

            userService.save(entity);
        }
        return ResultData.success(Boolean.TRUE);
    }

    @DeleteMapping(value = "/user/del/{id}")
    public ResultData<Boolean> del(@PathVariable("id") Integer id)
    {
        return ResultData.success(userService.removeById(id));
    }

    @PutMapping(value = "/user/update")
    public ResultData<Boolean> update(@RequestBody User user)
    {

        User oldUser = userService.getBaseMapper().selectById(user.getId());

        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();

        updateWrapper
                .set(User::getUsername,user.getUsername())
                .set(User::getPassword,user.getPassword())
                .set(User::getSex,user.getSex())
                .set(User::getVersion,oldUser.getVersion()+1)
                .eq(User::getId,user.getId())
                .eq(User::getVersion,oldUser.getVersion());

        return ResultData.success(userService.update(updateWrapper));
    }


    @PutMapping(value = "/user/updateConcurrent")
    public ResultData<Boolean> updateConcurrent(@RequestBody User user)
    {
        User oldUser1 = userService.getBaseMapper().selectById(user.getId());
        User oldUser2 = userService.getBaseMapper().selectById(user.getId());

        oldUser1.setPassword("xxx");
        userService.getBaseMapper().updateById(oldUser1);

        oldUser2.setPassword("kkk");
        int count = userService.getBaseMapper().updateById(oldUser2);

        if(count == 0)
        {
            System.out.println("oldUser2=====update fail");
            return ResultData.success(Boolean.FALSE);
        }else{
            System.out.println("oldUser2=====update success");
            return ResultData.success(Boolean.TRUE);
        }
    }

    @GetMapping(value = "/user/get/{id}")
    public ResultData<User> getById(@PathVariable("id") Integer id)
    {
        if(id == -4) throw new RuntimeException("id不能为负数");

        if (id < 0) {
            throw new BusinessException(ReturnCodeEnum.REQPARAM_NEGATIVE.getCode(),ReturnCodeEnum.REQPARAM_NEGATIVE.getMessage());
        }
        return ResultData.success(userService.getById(id));
    }

    @GetMapping(value = "/user/list")
    public ResultData<List<User>> list()
    {
        return ResultData.success(userService.getBaseMapper().selectList(null));
    }

    // http://localhost:2401/user/get?username=%E9%AD%8F%E5%BB%B6
    @GetMapping(value = "/user/get")
    public ResultData<User> getByUseName(@RequestParam("username") String username)
    {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,username);

        return ResultData.success(userService.getOne(queryWrapper));
    }

    /**
     * @Description: MybatisPlus原生分页插件IPage增强
     * http://localhost:2401/user/selectPage?pageNum=2&pageSize=5
     */
    @GetMapping("/user/selectPage")
    public List<User> selectPage(@RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize)
    {
        IPage<User> page = new Page(pageNum,pageSize); //import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
        //获取当前页的数据
        return userService.page(page).getRecords();
    }

    /**
     * @Description: 故意报错演示trycf
     */
    @RequestMapping(value = "/pay/error",method = RequestMethod.GET)
    public ResultData<Integer> getPayError()
    {
        Integer i = Integer.valueOf(200);
        try
        {
            System.out.println("--------come here");
            int data = 10/0;
        }catch (Exception e){
            e.printStackTrace();
            return ResultData.fail(ReturnCodeEnum.RC500.getCode(),e.getMessage());
        }
        return ResultData.success(i);
    }


    // ==============test

/**
 ###
 POST http://localhost:2401/user/add
 Content-Type: application/json

 {
 "username": "诸葛亮",
 "password": "123456",
 "sex": "1"
 }

 ###
 PUT http://localhost:2401/user/update
 Content-Type: application/json

 {
 "id": 2,
 "username": "张飞",
 "password": "777888",
 "sex": "1",
 "createTime": "2027-06-21 17:59:59"
 }
 */

}
